package com.androidservice.dao;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.androidservice.bean.Advertisement;

@Repository
public class AdvertisementDao extends AbstractDao<Advertisement>{

	public AdvertisementDao() {
		super(Advertisement.class);
	}
	
	@SuppressWarnings("unchecked")
	public List<Advertisement> findAllAdvert(){
		Query query = entityManager.createQuery("select a from Advertisement a where a.checkstatus = '0'order by a.aid");
		return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<Advertisement> findAllAdvertisement(){
		Query query = entityManager.createQuery("select a from Advertisement a order by a.aid");
		return query.getResultList();
	}
	
	public void DeleteAdvertByAid(int aid){
		Query query = entityManager.createQuery("delete from Advertisement a where a.aid = ?1");
		query.setParameter(1, aid);
		
		query.executeUpdate();
	}
	
	public Advertisement findAdvertByAid(int aid){
		Query query = entityManager.createQuery("select a from Advertisement a where a.aid = ?1");
		query.setParameter(1, aid);
		
		return (Advertisement)query.getSingleResult();
	}
	
	public void saveAdvertisement(Advertisement adver){
		entityManager.merge(adver);
	}
	
	public void saveNewAdvertisement(Advertisement adver){
		entityManager.persist(adver);
	}
	
	public boolean findNumberAvert(){
		Query query = entityManager.createQuery("select a from Advertisement a where a.checkstatus = '0'order by a.aid");
		if(query.getResultList().size() >= 6){
			return false;
		}
		return true;
	}
	
	public boolean findAdverByBid(int bid){
		Query query = entityManager.createQuery("select a from Advertisement a where a.typeId = ?1 and a.type = '0'");
		query.setParameter(1, bid);
		if(query.getResultList().size() >= 0){
			return true;
		}
		return false;
	}
	public void deleteAdverByBid(int bid){
		Query query = entityManager.createQuery("delete from Advertisement a where a.typeId = ?1 and a.type = '0'");
		query.setParameter(1, bid);
		query.executeUpdate();
	}
	
	@SuppressWarnings("unchecked")
	public List<Advertisement> findAdverBycid(int cid){
		Query query = entityManager.createQuery("select a from Advertisement a where a.typeId = ?1 and a.type = '0'");
		query.setParameter(1, cid);
		
		return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<Advertisement> findAdvrByType(String type){
		Query query = entityManager.createQuery("select a from Advertisement a where a.type = ?1 order by a.aid");
		query.setParameter(1, type);
		
		return query.getResultList();
	}

}
